﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.IO;
using System.Windows.Data;
using System.Globalization;
using System.Xml.Linq;

namespace ControlExplorer.Controls.RichTextBox
{
    public partial class FacebookRSS : UserControl
    {
        private const string FACEBOOK_RSS = "http://www.facebook.com/feeds/page.php?id=131214763781&format=atom10";
        private const string NAMESPACE = "http://www.w3.org/2005/Atom";
        private FriendlyDateTimeConverter _fdc;


        public FacebookRSS()
        {
            InitializeComponent();
            _fdc = new FriendlyDateTimeConverter();
            GetFacebookFeedItems();
        }

        public void GetFacebookFeedItems()
        {
            DownloadStringAsync(FACEBOOK_RSS, facebook_DownloadStringCompleted);
        }

        private void DownloadStringAsync(string rss, DownloadStringCompletedEventHandler handler)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(new Uri(rss));
        }

        private void facebook_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Facebook RSS down at the moment. Try again later.");
            }
            else if (!string.IsNullOrEmpty(e.Result))
            {
                var result = XElement.Parse(e.Result);
                var feeds = from entry in result.Elements("{" + NAMESPACE + "}entry") select entry;
                
                // build html content
                string html = "";
                foreach (XElement xe in feeds)
                {
                    html += xe.Element(XName.Get("content", NAMESPACE)).Value;
                    html += "<br/><span style='color: #9C9A9C'>Posted ";
                    string published = xe.Element(XName.Get("published", NAMESPACE)).Value;
                    DateTimeOffset dateOffset;
                    if (DateTimeOffset.TryParse(published, out dateOffset))
                    {
                        html += _fdc.Convert(dateOffset.UtcDateTime, typeof(string), null, null);
                    }
                    html += " by ComponentOne</span><br/>===============================<br/>";
                }

                // set total html to C1RTB
                c1RichTextBox1.Html = html;

                // collapse progress bar
                c1ProgressBar1.Visibility = System.Windows.Visibility.Collapsed;
            }


        }

        private void c1RichTextBox1_RequestNavigate(object sender, C1.Phone.RichTextBox.RequestNavigateEventArgs e)
        {
            if (e.Hyperlink.NavigateUri.IsAbsoluteUri)
            {
                App.WebPageNavigate(e.Hyperlink.NavigateUri.AbsoluteUri);
            }
            else
            {
                // handle relative facebook urls
                App.WebPageNavigate("http://www.facebook.com" + e.Hyperlink.NavigateUri.OriginalString);
            }
        }
    }

    /// <summary>
    /// Converts a DateTime value to a friendly string like "8 hours ago" using UTC time
    /// </summary>
    public class FriendlyDateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && value.GetType().Equals(typeof(DateTime)))
            {
                string totalTime = "";
                TimeSpan ts = DateTime.UtcNow - (DateTime)value;

                if (ts.Days > 1)
                {
                    totalTime = totalTime + ts.Days.ToString() + " days ";
                }
                else if (ts.Days == 1)
                {
                    totalTime = totalTime + "1 day ";
                }
                else
                {
                    if (ts.Hours > 1)
                    {
                        totalTime = totalTime + ts.Hours.ToString() + " hours ";
                    }
                    else if (ts.Hours == 1)
                    {
                        totalTime = totalTime + "1 hour ";
                    }
                    else
                    {
                        totalTime = totalTime + ts.Minutes.ToString() + " mins ";
                    }
                }

                totalTime = totalTime + "ago";
                return totalTime;
            }
            else
            {
                return value.ToString();
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
